package com.metacube.metaconnect.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.metacube.metaconnect.Service.UserInformationService;
import com.metacube.metaconnect.model.SignUpStep2Form;

public class SignUpStep2Action extends Action {

	/*
	 * insert the data of user to userinformation table in database
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		SignUpStep2Form step2form = (SignUpStep2Form) form;

		FileOutputStream outputStream = null;
		FormFile formFile = null;

		try {
			String imgName = null;
			formFile = step2form.getFile();
			String res = formFile + "";
			if (!res.equals("")) {

				imgName = request.getSession().getAttribute("emailId")
						+ formFile.getFileName().substring(
								formFile.getFileName().lastIndexOf("."));
				String path = getServlet().getServletContext().getRealPath(
						"Upload")
						+ "\\" + imgName;
				outputStream = new FileOutputStream(new File(path));
				outputStream.write(formFile.getFileData());
			}
			String email = request.getSession().getAttribute("emailId")
					.toString();

			Date dob = Date.valueOf(request.getParameter("dob"));

			boolean result = new UserInformationService().insertUserInfoStep2(
					step2form, email, dob, imgName);

			if (result) {
				request.getSession().removeAttribute("signupstep2");
				return mapping.findForward("success");
			} else
				return mapping.findForward("failure");
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}

	}
}
